<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addPermissionFn(1, '0')">添加权限</el-button>
        </div>

        <el-table border :data="allPermissionList" row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-button v-if="row.type === 1" type="text" @click="addPermissionFn(2, row.id)">添加</el-button>
              <el-button type="text" @click="editPermissionFn(row.id)">编辑</el-button>
              <el-button type="text" @click="delPermissionFn(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 弹窗 -->
        <per-dialog ref="perDialog" :is-edit="isEdit" :permission-list="permissionList" @addPerEV="addPerFn" />
      </el-card>
    </div>
  </div>
</template>

<script>
import { getPermissionListAPI, addPermissionAPI, getPermissionDetailAPI, updatePermissionAPI, delPermissionAPI } from '@/api'
import { transTree } from '@/utils'
import perDialog from './component/perDialog.vue'
export default {
  components: {
    perDialog
  },
  data() {
    return {
      allPermissionList: [], // 所有权限列表
      permissionList: [], // 所有扁平
      isEdit: false // 是否为编辑状态 添加还是编辑
    }
  },
  created() {
    // 获取权限列表
    this.getPermissionListFn()
  },
  methods: {
    // 获取所有权限点列表
    async getPermissionListFn() {
      const res = await getPermissionListAPI()
      console.log(res)
      this.permissionList = res.data
      this.allPermissionList = transTree(res.data, '0') // 参数2，传递父级id（递归找子对象）让pid为’0‘的对象，在数组的第一层
    },
    // 点击添加权限按钮 弹窗出现
    addPermissionFn(type, pid) {
      this.isEdit = false
      // type右上角按钮传下来的1，页面权限点右边添加，传下来的是2（type值作为新对象的type值使用）
      // pid右上角按钮传下来的'0'，页面权限点右边添加，传下来的是行的id值
      this.$refs.perDialog.showDialog = true
      this.$refs.perDialog.formData.type = type
      this.$refs.perDialog.formData.pid = pid
    },
    // 执行添加权限的接口操作
    async addPerFn(formData) {
      if (this.isEdit) { // 编辑
        await updatePermissionAPI(formData)
      } else { // 新增
        const res = await addPermissionAPI(formData)
        console.log(res)
      }

      this.getPermissionListFn()
    },
    // 编辑权限
    async editPermissionFn(roleId) {
      this.isEdit = true
      this.$refs.perDialog.showDialog = true
      const res = await getPermissionDetailAPI(roleId)
      console.log(res)
      this.$refs.perDialog.formData = res.data
    },
    // 删除权限
    async delPermissionFn(perId) {
      await delPermissionAPI(perId)
      this.getPermissionListFn()
    }
  }
}
</script>

<style lang="scss" scoped></style>
